﻿using UnityEngine;
using System;
using System.IO;

/// <summary>
/// 日志管理器
/// </summary>
public class LoggerMgr : UnitySingleton<LoggerMgr>
{
    private StreamWriter logWriter;
    private string logFilePath;

    [Header("日志设置")]
    public bool enableFileLogging = true;
    public bool enableConsoleLogging = true;
    public LogLevel logLevel = LogLevel.Verbose;

    public enum LogLevel
    {
        Verbose,
        Debug,
        Info,
        Warning,
        Error,
        Critical
    }

    protected void Awake()
    {
        if (enableFileLogging)
        {
            string logDir = Path.Combine(Application.persistentDataPath, "Logs");
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }

            string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
            logFilePath = Path.Combine(logDir, $"game_log_{timestamp}.txt");
            logWriter = new StreamWriter(logFilePath, true);

            Application.logMessageReceived += HandleUnityLog;
        }
    }

    private void OnDestroy()
    {
        if (logWriter != null)
        {
            logWriter.Close();
            logWriter = null;
        }
    }

    private void HandleUnityLog(string condition, string stackTrace, LogType type)
    {
        if (!enableFileLogging) return;

        string logEntry = $"[{DateTime.Now:HH:mm:ss.fff}] [{type}] {condition}\n{stackTrace}";
        logWriter.WriteLine(logEntry);
        logWriter.Flush();
    }

    public void Log(object message, LogLevel level = LogLevel.Info)
    {
        if (level < logLevel) return;

        string formatted = $"[{DateTime.Now:HH:mm:ss.fff}] [{level}] {message}";

        if (enableConsoleLogging)
        {
            switch (level)
            {
                case LogLevel.Warning:
                    Debug.LogWarning(formatted);
                    break;
                case LogLevel.Error:
                case LogLevel.Critical:
                    Debug.LogError(formatted);
                    break;
                default:
                    Debug.Log(formatted);
                    break;
            }
        }

        if (enableFileLogging && logWriter != null)
        {
            logWriter.WriteLine(formatted);
            logWriter.Flush();
        }
    }
}